package com.felk.kafka.java;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Arrays;
import java.util.Properties;

public class E2_KafkaConsumer implements Runnable {

    private final KafkaConsumer<String, String> consumer;
    private ConsumerRecords<String, String> msgList;
    private final static String topic = "kafkabase_test";
    private static final String GROUPID = "groupA";

    public static void main(String args[]) {
        new Thread(new E2_KafkaConsumer()).start();
    }

    {
        Properties props = new Properties();
        props.put("bootstrap.servers", "192.168.56.101:9092");
        props.put("group.id", GROUPID);
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");
        props.put("session.timeout.ms", "30000");
        props.put("auto.offset.reset", "earliest");
        props.put("key.deserializer", StringDeserializer.class.getName());
        props.put("value.deserializer", StringDeserializer.class.getName());
        this.consumer = new KafkaConsumer<String, String>(props);
        this.consumer.subscribe(Arrays.asList(topic));
    }

    @Override
    public void run() {
        int messageNo = 1;
        System.out.println("---------开始消费---------");
        try {
            for (; ; ) {
                msgList = consumer.poll(1000);
                if (null != msgList && msgList.count() > 0) {
                    for (ConsumerRecord<String, String> record : msgList) {
                        System.out.print("-------receive------");
                        System.out.print("topic: " + record.topic());
                        System.out.print(",partition: " + record.partition());
                        System.out.print(",key: " + record.key());
                        System.out.print(",value: " + record.value());
                        System.out.print(",offset: " + record.offset());
                        System.out.print(",timestamp: " + record.timestamp());
                        System.out.println(",headers:  " + record.headers());
                        //当消费了1000条就退出
                        if (messageNo % 949 == 0) {
                            return;
                        }
                        messageNo++;
                    }
                    consumer.commitSync();
                } else {
                    Thread.sleep(1000);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            consumer.close();
        }
    }

}